package org.clockwise.feature;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.clockwise.driver.LinkerDriver;
import org.clockwise.util.MyFileReader;

/**
 * This class holds all the account info, providing HashMap
 * to get account by id or name.
 * @author WangYan
 *
 */
public class AccountPool implements Serializable {
	
	public HashMap<Long, Account> userDict = null;				// the dictionary to search user by id
	// dictionary based on name segments is deprecated
	// because it consumes too much memory with poor effect
//	private HashMap<String, Set<Long>> nameDict = null;			// the dictionary to search user by name
	private List<Account> userList = null;
	
	private HashSet<String> nonsense = null;
	
	public AccountPool(HashMap<Long, Account> dict) {
		userDict = dict;
		userList = new ArrayList<Account>();
		for (Long id : dict.keySet()) {
			userList.add(userDict.get(id));
		}
		nonsense = new HashSet<String>();
		String ignoreWordsFile = LinkerDriver.DATA_DIR + "IgnoreWords.txt";
		MyFileReader mfr = new MyFileReader(ignoreWordsFile);
		String temp = null;
		while ((temp = mfr.getNextLine()) != null) {
			nonsense.add(temp.trim());
//			System.out.println(temp.trim() + " is added");
		}
	}
	
	private int contains(int start, String[] src, String target) {
		if (start < 0) {
			return start;
		}
		for (int i = start; i < src.length; i++) {
			if (target.equals(src[i])) {
				return i;
			}
		}
		return -1;
	}
	
	private int contains(int start, String src, String target) {
		if (start < 0) {
			return start;
		}
		return src.indexOf(target, start);
	}
	
	public List<Account> getPotentialList(String keyword, String[] segWord, String[] segLabel) {
		List<Account> list = new ArrayList<Account>();
		Iterator<Account> iter = userList.iterator();
		while (iter.hasNext()) {
			Account user = iter.next();
			boolean isAdd = true;
			int namePos = 0, infoPos = 0;
			for (int i = 0; i < segWord.length; i++) {
				if (segLabel[i].startsWith("w")) {
					continue;
				}
				if (nonsense.contains(segWord[i])) {
					continue;
				}
				namePos = contains(namePos, user.nameSegWord, segWord[i]);
				infoPos = contains(infoPos, user.infoSegWord, segWord[i]);
				
				if (namePos < 0 && infoPos < 0) {
					isAdd = false;
					break;
				}
			}
			if (!isAdd) {
				if (contains(0, user.nameSegWord, keyword) >= 0 ||
					contains(0, user.infoSegWord, keyword) >= 0) {
					isAdd = true;
				}
			}
			if (isAdd) {
				list.add(user);
			}
		}
		return list;
	}
	
}
